{% extends 'marketing/base.html' %}
{% load static %}
{% load paginate %}
{% block content %}
{{ block.super }}

<nav aria-label="breadcrumb">
  <ol class="breadcrumb mb-3">
    <li class="breadcrumb-item"><a href="{% url 'marketing:campaign_list' %}">Campaigns</a></li>
    <li class="breadcrumb-item active">{% if campaign_obj %}Edit{% else %}Create{% endif %} Email Template</li>
  </ol>
</nav>
<div class="main_container ml-5 mr-5">
  <div class="row marl">
    <div class="col-md-12">
      <form id="add_form" method="POST" action='' novalidate enctype="multipart/form-data">
        <div class="overview_form_block row marl justify-content-center">
          <div class="col-md-12">
            <div class="card">
              <div class="card-body">
                <div class="card-title text-center">
                  Create Campaign
                </div>
                <form>
                  <div class="row marl">
                    <div class="col-md-12">
                      <div class="form-group">
                        <label>Title</label><span class="error_marker" style="color:red"> *</span>
                        <input type="text" name="title" class="form-control" placeholder="Title of this campaign">
                        
                        <span id="id_title"></span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group">
                        <label>Select Template</label>
                        <select class="form-control js-example-basic-single email-template-select" name="email_template"
                          id="select_template">
                          <option value="">Select a template</option>
                          {% for email_template in email_templates %}
                          <option value="{{email_template.id}}" htmlcode="{{email_template.html}}"
                            subject="{{email_template.subject}}">{{ email_template.title }}</option>
                          {% endfor %}
                          
                        </select>
                        <span id="id_email_template"></span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group">
                        <label>Subject</label><span class="error_marker" style="color:red"> *</span>
                        <input type="text" name="subject" class="form-control" placeholder="Subject of this Campaign">
                        
                        <span id="id_subject"></span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group">
                        <label>From Name</label><span class="error_marker" style="color:red"> *</span>
                        <input type="text" class="form-control" placeholder="John Doe" name="from_name">
                        <span id="id_from_name"></span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group">
                        <label>From Email</label><span class="error_marker" style="color:red"> *</span>
                        <input type="email" class="form-control" placeholder="support@mp.com" name="from_email">
                        <span id="id_from_email"></span>
                      </div>
                    </div>
                    <div class="col-md-12">
                      <div class="row">
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Select Contact List</label><span class="error_marker" style="color:red"> *</span>
                            <select class="contact-lsit-select js-example-basic-multiple" name="contact_list"
                              multiple="multiple">
                              {% for contact_list in contact_lists %}
                              <option value="{{contact_list.id}}">{{ contact_list.name }}</option>
                              {% endfor %}
                            </select>
                            <span id="id_contact_list"></span>
                          </div>
                          <div class="form-group">
                            <label><input type="checkbox" name="reply_to_crm" value="true"> Reply To CRM</label>
                            <span id="id_reply_to_crm"></span>
                          </div>
                          <div class="form-group reply_to_email">
                            <label>Reply to email</label><span class="error_marker" style="color:red"> *</span>
                            <input type="email" class="form-control" placeholder="replyto@mp.com" name="reply_to_email">
                            <span id="id_reply_to_email"></span>
                          </div>
                          
                          <div class="form-group">
                            <label>Attachments</label>
                            <input type="file" class="form-control" name="attachment">
                            <small class="form-text text-muted">Allowed file types: jpeg, jpg, gif, png, pdf,
                              zip</small>
                            <span id="id_attachment"></span>
                          </div>

                          
                          <div class="form-group">
                            <label>Tags</label>
                            <div class="txt-box-div" id="tag-div">
                              <input type="text" name="tags" id="tags_1" class="tags"
                                value="{% if contact_list %}{% for tag in contact_list.tags.all %}{{tag.name}}, {% endfor %}{% endif %}" />
                            </div>
                            <span id="id_tags"></span>
                          </div>
                          
                          
                          <br>
                          <div class="form-group">
                            <div class="row marl buttons_row text-center form_btn_row">
                              <button type="submit" class="btn btn-default save">Save Campaign</button>
                              <a href="{% url 'marketing:campaign_list' %}" class="btn btn-default clear">Cancel</a>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-9">
                          <div class="row">
                            <div class="col-md-4">
                              <div class="form-group">
                                <label><input type="checkbox" name="schedule_later" value="true"> Schedule Later</label>
                                <span id="id_schedule_later"></span>
                              </div>
                            </div>
                            <div class="col-md-4 timezone-div" style="display: none;">
                              <div class="form-group">
                                <label>Timezone</label>
                                <select name="timezone" id="timezone"
                                  class="form-control timezone-select js-example-basic-single">
                                  <option value="">Select a Timezone</option>
                                  {% for timezone in timezones %}
                                  <option value="{{timezone.0}}"
                                    {% if timezone.0 == settings_timezone %}selected{% endif %}>{{timezone.1}}</option>
                                  {% endfor %}
                                </select>
                                <span id="id_timezone"></span>
                              </div>
                            </div>
                            <div class="col-md-4 timezone-div" style="display: none;">
                              <div class="form-group">
                                <label for="">Schedule Date Time</label><span class="error_marker" style="color:red">
                                  *</span>
                                <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
                                  <input type="text" class="form-control datetimepicker-input"
                                    data-target="#datetimepicker1" name="schedule_date_time" />
                                  <div class="input-group-append" data-target="#datetimepicker1"
                                    data-toggle="datetimepicker">
                                    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                                  </div>
                                </div>
                                
                                <span id="id_schedule_date_time"></span>
                              </div>
                            </div>
                          </div>
                          <div class="col-md-12">
                            
                            <div class="form-group">
                              <label>Html Code</label><span class="error_marker" style="color:red"> *</span>
                              <span id="id_html"></span>
                              <div id="editor-container">
                              </div>
                              
                              <input type="hidden" name="html" id="html_content">
                            </div>
                            <div class="col-md-12 no-padding">
                              
                              
                              <div class="col-md-12">
                                <div class="heading">Personalization tags</div>
                                <p class="desc">The following tags can be used on both Plain text or HTML. Add these tags to customize the email template, these tags will be replaced with the associated contact details while the mails are sent.</p>
                                <ul>
                                  <li>
                                    <strong>First Name: </strong>
                                    <code>{% templatetag openvariable %} first_name {% templatetag closevariable %}</code>
                                  </li>
                                  <li>
                                    <strong>Last Name: </strong>
                                    <code>{% templatetag openvariable %} last_name {% templatetag closevariable %}</code>
                                  </li>
                                  <li>
                                    <strong>Full Name: </strong>
                                    <code>{% templatetag openvariable %} name {% templatetag closevariable %}</code>
                                  </li>
                                  <li>
                                    <strong>Email: </strong>
                                    <code>{% templatetag openvariable %} email {% templatetag closevariable %}</code>
                                  </li>
                                  <li>
                                    <strong>Company: </strong>
                                    <code>{% templatetag openvariable %} company_name {% templatetag closevariable %}</code>
                                  </li>
                                  <li>
                                    <strong>City: </strong>
                                    <code>{% templatetag openvariable %} city {% templatetag closevariable %}</code>
                                  </li>
                                  <li>
                                    <strong>State: </strong>
                                    <code>{% templatetag openvariable %} state {% templatetag closevariable %}</code>
                                  </li>
                                  
                                </ul>
                              </div>
                              
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock %}
{% block js_block %}
<script>

  $.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
  }


  // $('[name="schedule_date_time"]').datetimepicker({format: 'yyyy-mm-dd hh:ii'});
  $(function () {

    $(function () {
      $('#tags_1').tagsInput({ width: 'auto' });
    });

    $.fn.datetimepicker.Constructor.Default = $.extend({}, $.fn.datetimepicker.Constructor.Default, {
      icons: {
        time: 'fa fa-clock',
        date: 'fa fa-calendar',
        up: 'fa fa-arrow-up',
        down: 'fa fa-arrow-down',
        previous: 'fa fa-chevron-left',
        next: 'fa fa-chevron-right',
        today: 'far fa-calendar-check-o',
        clear: 'fa fa-trash',
        close: 'fa fa-times'
      }
    });
    $('#datetimepicker1').datetimepicker({
      format: "YYYY-MM-DD HH:mm"
    });
  });

  $(document).ready(function () {
    $(".email-template-select").select2({
      placeholder: "Select an email template"
    })
    $(".contact-lsit-select").select2({
      placeholder: "Select a contact list",
      tags: "true",
      allowClear: true
    });
    $(".timezone-select").select2({
      placeholder: "Select a Timezone",
    });
  });
  var quill = new Quill('#editor-container', {
    modules: {
      toolbar: [
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        // ['image', 'code-block']
        ['code-block', 'link']
      ]
    },
    placeholder: 'Compose an epic...',
    theme: 'snow' // or 'bubble'
  });

  quill.on('text-change', function () {
    $('.ql-syntax').css({ "background-color": "#23241f", "color": "#f8f8f2", "overflow": "visible", "border-radius": "3px", "white-space": "pre-wrap", "margin-bottom": "5px", "margin-top": "5px", "padding": "5px 10px" })
    var justHtml = quill.root.innerHTML;
    $('#html_content').val(justHtml);
  });

  $('[name="email_template"]').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;
    var subject = $('[name="subject"]');
    var html_code = $("#editor-container");
    var html_content = $('#html_content');
    if ($(optionSelected).val()) {
      subject.val($(optionSelected).attr("subject"));
      quill.root.innerHTML = $(optionSelected).attr("htmlcode");
    } else {
      subject.val("");
      quill.root.innerHTML = "";
      html_content.val("");
    }
  })

  selectedEmail = $.urlParam('email_template')
  if (selectedEmail) {
    $('#select_template option[value="' + selectedEmail + '"]').attr('selected', 'true')
    var optionSelected = $('#select_template option[value="' + selectedEmail + '"]');
    var valueSelected = selectedEmail;
    var subject = $('[name="subject"]');
    var html_code = $("#editor-container");
    var html_content = $('#html_content');
    if ($(optionSelected).val()) {
      subject.val($(optionSelected).attr("subject"));
      quill.root.innerHTML = $(optionSelected).attr("htmlcode");
    } else {
      subject.val("");
      quill.root.innerHTML = "";
      html_content.val("");
    }
  }

  $('[name="schedule_later"]').on('change', function (e) {
    if ($(this).is(":checked")) {
      $('.timezone-div').show();
    } else {
      $('.timezone-div').hide();
    }
  })

  $('[name="reply_to_crm"]').on('change', function (e) {
    if ($(this).is(":checked")) {
      $('.reply_to_email').hide();
    } else {
      $('.reply_to_email').show();
    }
  })

  $('.save_btn').click(function (e) {
    e.preventDefault();
    $("form#add_form").submit()
  })

  $('form#add_form').ajaxForm({
    type: 'POST',
    // dataType: 'json',
    url: $(this).attr('action'),
    data: $(this).serialize(),
    success: function (data) {
      console.log("data", data)
      if (data.error == false) {
        window.location = "{% url 'marketing:campaign_list' %}";
      } else {
        /*$(document).ajaxStop($.unblockUI);*/
        // $.unblockUI();
        $('p.failure').remove();
        for (var key in data.errors) {
          $('#id_' + key).html('<p class="error failure"> *' + data.errors[key] + '</p>');
        }
      }
    },
    error: function (xhr, errmsg, err) {
      console.log('error data', errmsg, err)
    }
  });
</script>
{% endblock js_block %}